'use strict';
var domain 	= require('domain');
var express = require('express');
var path 		= require('path');
var gm 			= require('gm');
var bodyParser 		= require('body-parser');
var busboy 				= require('connect-busboy');
var request 			= require('request');
var multiparty 		= require('multiparty');
var AV 						= require('leanengine');

var http		= require('http');
var ejs 		= require('ejs');
var fs 			= require('fs');
var os 			= require('os');

//自定义函数及控制器
var cMain		= require('./controllers/main');
var cMy			= require('./controllers/my');
var cAdmin	= require('./controllers/admin');
var cAdminNews		= require('./controllers/admin_news');
var cAdminTag			= require('./controllers/admin_tag');
var cAdminUser		= require('./controllers/admin_user');
var cAdminImage		= require('./controllers/admin_image');
var cAdminTrip		= require('./controllers/admin_trip');
var cAdminComment	= require('./controllers/admin_comment');
var cAdminReport	= require('./controllers/admin_report');
var cAdminSetting	= require('./controllers/admin_setting');



var cloud 	= require('./cloud');

var avImage = AV.Object.extend("Image");



var app 	= express(),
	  admin	= express();

// 设置 view 引擎

app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');

				// 设置模板目录
admin.set('views',path.join(__dirname, 'views/admin'));   // 设置模板目录

app.use(express.static('public'));

app.use(AV.Cloud);
app.use(busboy());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// 未处理异常捕获 middleware
app.use((req, res, next) => {
  let d = domain.create();
  d.add(req);
  d.add(res);
  d.on('error', (err) => {
    console.error('uncaughtException url=%s, msg=%s', req.url, err.stack || err.message || err);
    if (!res.finished) {
      res.statusCode = 500;
      res.setHeader('content-type', 'application/json; charset=UTF-8');
      res.end('uncaughtException');
    }
  });
  d.run(next);
});

app.use(AV.Cloud.CookieSession({secret: 'MyFightPix', maxAge: 3600000,fetchUser:true}));

app.get('/', cMain.homePage);//网站首页

app.get(/^\/(((tmp)|(css))\/)+([a-zA-Z0-9.-_]+(\.html)+)?$/i,cMain.htmlPage);//静态页面

//获取.css及.js文件
app.all(/^\/tmp\/views\/([a-zA-Z0-9\.\-]+((.css)|(.js)))?$/i, function(req,res,next){
	res.type(req.params[1]);
	res.sendfile("/tmp/views/"+req.params[0]);
});

//获取图片文件
app.get('/p', function(req,res,next){
	var id		= req.query.id;
	//console.log("id="+id);
	var queryImage=new AV.Query(avImage);
	queryImage.equalTo("objectId",id);
	queryImage.first(function(image){
		//console.dir(image);
		//console.log(typeof(image.get("file")));
		if(typeof(image)=="undefined" || image==null || typeof(image.get("file"))!="object"){
			res.redirect("/i/default.png");
		}else{
			var file	= image.get("file");
			var w		= req.query.w;
			var h		= req.query.h;
			if(w && h && w>0 && h>0){
				res.redirect(file.thumbnailURL(w,h));
			}else{
				res.redirect(file.url());
			}
		}
	});
});

app.get('/p/m', function(req,res,next){
	var id		= req.query.id;
	//console.log("id="+id);
	var queryImage=new AV.Query(avImage);
	queryImage.equalTo("objectId",id);
	queryImage.first(function(image){
		//console.dir(image);
		//console.log(typeof(image.get("file")));
		if(typeof(image)=="undefined" || image==null || typeof(image.get("file"))!="object"){
			res.redirect("/i/default.png");
		}else if(image.get("thumb")){
			var file	= image.get("thumb");
			res.redirect(file.url());
		}else{
			var file	= image.get("file");
			var url 	= file.url();
			var	tmpdir			= os.tmpdir();
			var ext					= path.extname(url);
			var tmp_path 		= path.join(tmpdir,image.id+ext);
			var targetPath	= path.join(tmpdir,"m_"+image.id+ext);
			if(!fs.existsSync(tmp_path)){
				request(url, function(err, response, body) {
						if(fs.existsSync(tmp_path) && !fs.existsSync(targetPath)){
							var imageMagick = gm.subClass({imageMagick : true });
							var im					= imageMagick(tmp_path);
							im.resize(640)
							.quality(80)
							.autoOrient()
			        .toBuffer(function (err,Buffer) {
								if(!err){
									var avFile  = new AV.File("m_"+image.id+ext,{base64:Buffer.toString('base64')});
									avFile.save().then(function(obj) {
										//fs.unlink(targetPath);
										image.set("thumb",obj);
										image.save();
									}, function(error) {
										console.error(error);
									});
									res.set('Content-Type', 'image/jpeg');
									res.send(Buffer);
								}else{
									res.redirect("/i/default.png");
								}
			        });
						}else{
							res.redirect("/i/default.png");
						}
				}).pipe(fs.createWriteStream(tmp_path));
			}else{
				res.redirect(targetPath);
			}
		}
	});
});

app.get('/p/s', function(req,res,next){
	var id		= req.query.id;
	//console.log("id="+id);
	var queryImage=new AV.Query(avImage);
	queryImage.equalTo("objectId",id);
	queryImage.first(function(image){
		//console.dir(image);
		//console.log(typeof(image.get("file")));
		if(typeof(image)=="undefined" || image==null || typeof(image.get("file"))!="object"){
			res.redirect("/i/default.png");
		}else if(image.get("cover")){
			var file	= image.get("cover");
			res.redirect(file.url());
		}else{
			var file	= image.get("file");
			var url 	= file.url();
			var	tmpdir			= os.tmpdir();
			var ext					= path.extname(url);
			var tmp_path 		= path.join(tmpdir,image.id+ext);
			if(!fs.existsSync(tmp_path)){
				request(url, function(err, response, body) {
						if(fs.existsSync(tmp_path)){
							var imageMagick = gm.subClass({imageMagick : true });
							var im					= imageMagick(tmp_path);
							im.resize(250,250,"!")
							.quality(80)
							.autoOrient()
			        .toBuffer(function (err,Buffer) {
								if(!err){
									var avFile  = new AV.File("m_"+image.id+ext,{base64:Buffer.toString('base64')});
									avFile.save().then(function(obj) {
										//fs.unlink(targetPath);
										image.set("cover",obj);
										image.save();
									}, function(error) {
										console.error(error);
									});
									res.set('Content-Type', 'image/jpeg');
									res.send(Buffer);
								}else{
									res.redirect("/i/default.png");
								}
			        });
						}else{
							res.redirect("/i/default.png");
						}
				}).pipe(fs.createWriteStream(tmp_path));
			}else{
				var imageMagick = gm.subClass({imageMagick : true });
				var im					= imageMagick(tmp_path);
				im.resize(250,250,"!")
				.quality(80)
				.autoOrient()
				.toBuffer(function (err,Buffer) {
					if(!err){
						var avFile  = new AV.File("m_"+image.id+ext,{base64:Buffer.toString('base64')});
						avFile.save().then(function(obj) {
							//fs.unlink(targetPath);
							image.set("cover",obj);
							image.save();
						}, function(error) {
							console.error(error);
						});
						res.set('Content-Type', 'image/jpeg');
						res.send(Buffer);
					}else{
						res.redirect("/i/default.png");
					}
				});
			}
		}
	});
});

app.get('/login', cMain.loginPage);
app.get('/change', cMy.changeImagePage);
app.get('/register', cMain.registerPage);
app.get('/logout', cMain.logoutPage);
app.post('/login', cMain.doLogin);
app.post('/register', cMain.doRegister);

app.get('/news', cMain.newslistPage);
app.get('/news/detail', cMain.newsdetailPage);
app.get('/trip', cMain.triplistPage);
app.get('/trip/detail', cMain.tripdetailPage);
app.all('/search', cMain.searchPage);
app.all('/discover', cMain.discoverPage);
app.all('/image/detail', cMain.imageDetailPage);
app.all('/comment/list', cMain.commentListPage);
app.all('/getclicks', cMain.doGetClicks);
app.use('/my',cMy.doCkAuth);
app.get('/my', cMy.myIndexPage);
app.all('/my/photostream', cMy.myImageListPage);
app.get('/my/photo/detail', cMy.myImageDetailPage);
app.post('/my/photo/edit', cMy.doEditImage);
app.all('/my/photo/delete', cMy.doDeleteImage);
app.get('/my/photo/remove', cMy.doRemoveImage);
app.all('/my/album', cMy.myAlbumListPage);
app.get('/my/album/detail', cMy.myAlbumDetailPage);
app.get('/my/album/addphotos', cMy.doAddPhotos);
app.get('/my/trip', cMy.myTripListPage);
app.get('/my/trip/create', cMy.myCreateTripPage);
app.post('/my/trip/edit', cMy.doEditTrip);
app.post('/my/trip/delete', cMy.doDeleteTrip);
app.post('/my/tripnote/edit', cMy.doEditTripNote);
app.post('/my/tripnote/delete', cMy.doDeleteTripNote);
app.get('/my/favorite', cMy.myFavoriteListPage);
app.get('/my/comment', cMy.myCommentListPage);
app.get('/my/uploadimg', cMy.myUploadPage);
app.post('/my/sendcommtent', cMy.doComment);
app.post('/my/togglefav', cMy.doToggleFav);
app.post('/my/checkfav', cMy.doCheckFav);
app.post('/my/upload', cMy.doUpload);
app.post('/my/createalbum', cMy.doCreateAlbum);
app.post('/my/trip/create', cMy.doCreateTrip);
app.post('/my/setavatar', cMy.doSetAvatar);


/*
后台管理
*/
app.get('/admin-login', cAdmin.loginPage);	//登录页面
app.post('/admin-login', cAdmin.doLogin);	//登录帐号
app.get('/admin-logout',cAdmin.doLogout);	//登出帐号

app.use('/admin', admin);
admin.use(cAdmin.doCkAuth);					//权限检查

admin.post('/uploadImg', function(req,res,next){
	var form = new multiparty.Form();
  form.parse(req, function(err, fields, files) {
		//console.log(files);
		var iconFile = files.uploadImg[0];
    fs.readFile(iconFile.path, function(err, data){
			//console.log(iconFile.path);
      if(err) {
        console.log(err);
      }else{
        var f = new AV.File(iconFile.originalFilename, data);
        f.save().then(function(fileObj) {
					var image=new avImage();
					image.set("file",fileObj);
					image.set("user",req.AV.user);
					image.set("isSys",true);
					return image.save();
				}).then(function(image){
					//console.log(image.get("user"));
					res.json({success:true,id:image.id,file_path:"/p?w=800&id="+image.id});
				}, function(error) {
					console.error(error.message);
					res.json({success:false,msg:"上传失败！"});
				});
			}
    });
  });
});

admin.get('/index', cAdmin.indexPage);					//后台索引页面
admin.get('/count', cAdmin.ajaxCount);
admin.get('/config/tags', cAdminTag.tagPage);
admin.get('/config/newbanner', cAdminSetting.newBannerPage);
admin.get('/config/homecatagory', cAdminSetting.homeCatagoryPage);
admin.get('/news/list', cAdminNews.listPage);
admin.get('/news/edit', cAdminNews.detailPage);
admin.get('/user/list', cAdminUser.listPage);
admin.get('/user/edit', cAdminUser.detailPage);
admin.get('/image/list', cAdminImage.listPage);
admin.get('/image/detail', cAdminImage.detailPage);
//admin.get('/image/edit', cAdminImage.detailPage);
admin.get('/trip/list', cAdminTrip.listPage);
admin.get('/comment/list', cAdminComment.listPage);
admin.get('/report/list', cAdminReport.listPage);
//admin.get('/trip/edit', cAdminTrip.detailPage);
admin.post('/config/savetags', cAdminTag.doSaveTag);
admin.post('/config/saveBanner', cAdminSetting.doSaveBanner);
admin.post('/config/saveCatagory', cAdminSetting.doSaveCatagory);
admin.post('/config/getItem', cAdminSetting.doGetItem);
admin.post('/news/save', cAdminNews.doSave);
admin.post('/news/delete', cAdminNews.doDelete);
admin.post('/user/new', cAdminUser.doCreate);
admin.post('/user/delete', cAdminUser.doDelete);
admin.post('/image/delete', cAdminImage.doDelete);
admin.post('/image/set', cAdminImage.doSet);
admin.post('/trip/delete', cAdminTrip.doDelete);
admin.post('/trip/set', cAdminTrip.doSet);
admin.post('/comment/delete', cAdminComment.doDelete);
admin.post('/comment/set', cAdminComment.doSet);
admin.post('/report/delete', cAdminReport.doDelete);
admin.post('/report/set', cAdminReport.doSet);





// 如果任何路由都没匹配到，则认为 404
// 生成一个异常让后面的 err handler 捕获
app.use(function(req, res, next) {
  res.status(404).render('404.html', {title: 'Sorry, page not found'});
});

// 如果是开发环境，则将异常堆栈输出到页面，方便开发调试
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) { // jshint ignore:line
    var statusCode = err.status || 500;
    if(statusCode === 500) {
      console.error(err.stack || err);
    }
    res.status(statusCode);
    res.render('error', {
      message: err.message || err,
      error: err
    });
  });
}

// 如果是非开发环境，则页面只输出简单的错误信息
app.use(function(err, req, res, next) { // jshint ignore:line
  res.status(err.status || 500);
  res.render('error', {
    message: err.message || err,
    error: {}
  });
});

module.exports = app;
